package com.txsj.scan.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.txsj.scan.R;
import com.txsj.scan.activity.InventoryBatchActivity;
import com.txsj.scan.adapter.GoodsLeftAdapeter;
import com.txsj.scan.adapter.PromotionNewAdapter;
import com.txsj.scan.base.BaseFragment;
import com.txsj.scan.bean.GoodsClassify;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryBatchBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.presenter.SelectGoodsListPresenter;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.view.ISelectGoodsListView;

import java.util.ArrayList;
import java.util.List;


/**
 * @Created by WangChuangJun on 2018/11/22
 * @Describe :商品列表页
 */
public class SelectGoodsListFragment extends BaseFragment<SelectGoodsListPresenter> implements ISelectGoodsListView {

    public static final int REQUEST_ADD_BATCH_CODE = 0x187;
    public static final int RESULT_COMMIT_BATCH_CODE = 0x188;

    private View view;
    private RecyclerView type_recyclerView,goods_recyclerView;
    private LinearLayout lay_bottom;
    private TextView tv_select_all_count,tv_commit;
    private XRefreshView xRefreshView;
    private GoodsLeftAdapeter leftAdapeter;
    PromotionNewAdapter goodsAdapter;

    List<InventoryBatchBean> commitBatchBeanList;//盘点选中的批次列表
    List<GoodsInfo> commitGoodsInfoList;//盘点选中的商品列表

    int pageNo = 1;
    int classifyPosition = 0;
    private String type;//1:当前仓库，2：其他仓库
    private WarehouseBean warehouseBean;

    @Override
    protected int layoutId() {
        return R.layout.fragment_select_goods_list;
    }

    @Override
    public void init() {
        initView();
        initData();
    }


    private void initData() {
        Bundle args = getArguments();
        type = args.getString("type");
        String json = args.getString("warehouse");
        warehouseBean = new Gson().fromJson(json,WarehouseBean.class);

        commitBatchBeanList = new ArrayList<>();
        commitGoodsInfoList = new ArrayList<>();

        if (type.equals("1")){
            lay_bottom.setVisibility(View.VISIBLE);
        }else {
            lay_bottom.setVisibility(View.GONE);
        }
        //初始化商品分类列表
        presenter.getGoodsTypeHttp(type,warehouseBean.getWarehouse_id()+"");
    }

    private void initView() {
        lay_bottom = (LinearLayout) rootView.findViewById(R.id.lay_bottom);
        tv_select_all_count = (TextView) rootView.findViewById(R.id.tv_select_all_count);
        tv_commit = (TextView) rootView.findViewById(R.id.tv_commit);

        type_recyclerView = (RecyclerView) rootView.findViewById(R.id.type_recyclerView);
        goods_recyclerView = (RecyclerView) rootView.findViewById(R.id.goods_recyclerView);
        xRefreshView = (XRefreshView) rootView.findViewById(R.id.xRefreshView);

        initEmptyView();
        xRefreshView.enableEmptyView(false);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setAutoLoadMore(true);

        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                pageNo = 1;
                if (leftAdapeter.getList().size()>0) {
                    presenter.getGoodsFilter(type, warehouseBean.getWarehouse_id(),leftAdapeter.getList().get(classifyPosition).getGoods_class_id());
                }

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                pageNo++;
                if (goodsAdapter.getList().size()%10 != 0 || leftAdapeter.getList().size() <= 0){
                    xRefreshView.stopLoadMore();
                    return;
                }
                presenter.getGoodsFilter(type, warehouseBean.getWarehouse_id(),leftAdapeter.getList().get(classifyPosition).getGoods_class_id());
            }
        });
        xRefreshView.startRefresh();

        type_recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        leftAdapeter = new GoodsLeftAdapeter(activity);
        type_recyclerView.setAdapter(leftAdapeter);
        leftAdapeter.setOnItemListener(new GoodsLeftAdapeter.OnItemListener() {
            @Override
            public void onClick(View v, int pos) {
                classifyPosition = pos;
                pageNo = 1;
                leftAdapeter.setSelect(pos);
                xRefreshView.startRefresh();
                presenter.getGoodsFilter(type, warehouseBean.getWarehouse_id(),leftAdapeter.getList().get(pos).getGoods_class_id());
            }
        });

        goods_recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        goodsAdapter = new PromotionNewAdapter(activity);
        goods_recyclerView.setAdapter(goodsAdapter);
        goodsAdapter.setOnSecondItemClickListener(new PromotionNewAdapter.ISetOnNewSecondClick() {
            @Override
            public void setOnSecondClick(View v, GoodsInfo secondGoods) {
                Intent intent = new Intent(activity,InventoryBatchActivity.class);
                intent.putExtra("data",new Gson().toJson(secondGoods));
                intent.putExtra("warehouse",new Gson().toJson(warehouseBean));
                intent.putExtra("from","GoodsListActivity");
                intent.putExtra("type",type);
                startActivityForResult(intent,REQUEST_ADD_BATCH_CODE);
            }

            @Override
            public void onCheckChange(boolean isSelect, int position) {
                goodsAdapter.updateRightData(isSelect,position);
            }
        });

        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("1")) {
                    clickOkCommit();
                }
            }
        });
    }

    /**
     * 确定提交盘点的商品
     */
    public void clickOkCommit(){
        if (commitBatchBeanList.size() == 0)return;
        Intent intent = activity.getIntent();
        intent.putExtra("data",new Gson().toJson(commitBatchBeanList));
        activity.setResult(RESULT_COMMIT_BATCH_CODE,intent);
        activity.finish();
    }

    /**
     * 刷新
     */
    public void refresh() {
        presenter.getGoodsTypeHttp(type,warehouseBean.getWarehouse_id()+"");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data || null ==data.getStringExtra("data"))return;
        if (requestCode == REQUEST_ADD_BATCH_CODE){
            String result_type = data.getStringExtra("type");
            if (result_type.equals("1")){//当返回来的数据是当前的仓库说明进行了盘点
                String json = data.getStringExtra("data");
                List<InventoryBatchBean> list = GsonFactory.getObjectList(json,InventoryBatchBean.class);
                String jsonGoodsInfo = data.getStringExtra("goods_info");
                GoodsInfo goodsInfo = new Gson().fromJson(jsonGoodsInfo,GoodsInfo.class);
                changeGoodsListSelectState(list,goodsInfo);
            }
        }
    }

    /**
     * 改变当前list的选中状态
     * @param list 要提交的集合
     * @param goodsInfo  改变的商品
     */

    private void changeGoodsListSelectState(List<InventoryBatchBean> list,GoodsInfo goodsInfo) {
        //合并已经存在的商品信息。没有就添加上
        boolean isContain = false;
        for (GoodsInfo info :commitGoodsInfoList){
            if (goodsInfo.getGoods_id()==info.getGoods_id()){
                isContain = true;
            }
        }
        if (!isContain){
            commitGoodsInfoList.add(goodsInfo);
        }
        for (int i = 0; i<goodsAdapter.getList().size();i++){
            for (GoodsInfo info :commitGoodsInfoList){
                if (goodsAdapter.getList().get(i).getGoods_id() == info.getGoods_id()){
                    goodsAdapter.updateRightData(true,i);
                    break;
                }
            }
        }

        //合并已经添加InventoryBatchList中的数据
        for(InventoryBatchBean inventoryBatchBean:list) {
            boolean isExit =false;
            for (InventoryBatchBean info : commitBatchBeanList) {
                if (inventoryBatchBean.getBatch_id()==info.getBatch_id()){
                    isExit = true;
                    info.setChange_num(inventoryBatchBean.getChange_num());
                    break;
                }
            }
            if (!isExit){
                commitBatchBeanList.add(inventoryBatchBean);
            }
        }
        tv_select_all_count.setText(commitGoodsInfoList.size()+"");
    }

    @Override
    public void onError(String msg) {
        t(msg);
        hideLoading();
        xRefreshView.stopRefresh();
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onClassifySuccess(List<GoodsClassify> data) {
        hideLoading();
        leftAdapeter.setData(data);
        leftAdapeter.setSelect(0);
        presenter.getGoodsFilter(type, warehouseBean.getWarehouse_id(),leftAdapeter.getList().get(classifyPosition).getGoods_class_id());
    }

    @Override
    public void onGoodsInfoListSuccess(List<GoodsInfo> data) {
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();
        if (null ==data || data.size() == 0){
            xRefreshView.enableEmptyView(true);
        }else {
            xRefreshView.enableEmptyView(false);
            goodsAdapter.setRightListData(data, pageNo, leftAdapeter.getList().get(classifyPosition).getClass_name());
        }

    }


    @Override
    public Context context() {
        return activity;
    }

    @Override
    protected SelectGoodsListPresenter providePresenter() {
        return new SelectGoodsListPresenter(this);
    }

    Button btn_empty_reload;

    /**
     * 列表数据为空时 显示的View
     */
    private void initEmptyView() {
        View emptyView = View.inflate(activity, R.layout.view_empty, null);
        btn_empty_reload = (Button) emptyView.findViewById(R.id.btn_empty_reload);
        xRefreshView.setEmptyView(emptyView);
        btn_empty_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRefreshView.startRefresh();
            }
        });
    }
}
